package com.xbongbong.lfasr.model;

import com.xbongbong.lfasr.util.Base64Encoder;
import com.xbongbong.lfasr.util.Md5Tool;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.Date;

@Setter
@Getter
@ToString
public class Signature {
    private String app_id;
    private String secret_key;
    private String signa;
    private String ts;

    public Signature(String app_id, String secret_key) throws SignatureException {
        this.app_id = app_id;
        this.secret_key = secret_key;
        this.ts = String.valueOf((new Date()).getTime() / 1000L);
        this.signa = HmacSHA1Encrypt(Md5Tool.MD5(app_id + this.ts), secret_key);
    }

    public Signature(String app_id, String secret_key, String signa, String ts) throws SignatureException {
        this.app_id = app_id;
        this.secret_key = secret_key;
        this.ts = ts;
        this.signa = signa;
    }

    private static String HmacSHA1Encrypt(String encryptText, String encryptKey) throws SignatureException {
        Object var2 = null;

        byte[] rawHmac;
        try {
            byte[] data = encryptKey.getBytes("UTF-8");
            SecretKeySpec secretKey = new SecretKeySpec(data, "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(secretKey);
            byte[] text = encryptText.getBytes("UTF-8");
            rawHmac = mac.doFinal(text);
        } catch (InvalidKeyException var7) {
            throw new SignatureException("InvalidKeyException:" + var7.getMessage());
        } catch (NoSuchAlgorithmException var8) {
            throw new SignatureException("NoSuchAlgorithmException:" + var8.getMessage());
        } catch (UnsupportedEncodingException var9) {
            throw new SignatureException("UnsupportedEncodingException:" + var9.getMessage());
        }

        Base64Encoder encoder = new Base64Encoder();
        String oauth = encoder.encode(rawHmac);
        return oauth;
    }

    public String getAppID() {
        return this.app_id;
    }

    public void setAppID(String app_id) {
        this.app_id = app_id;
    }

    public String getSecretKey() {
        return this.secret_key;
    }

    public void setSecretKey(String secret_key) {
        this.secret_key = secret_key;
    }
}
